﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using DaInterFace;
using DaInterFace.SYN;
using DaInterFace.SYN.E01;


namespace E01
{
    /// <summary>
    /// 同步销售调价
    /// </summary>
    public class A09 : ISYNChildSet
    {
        //string[] AccountISN;
        string strAccountISN = "";
        //字典—销售账户
        public static Dictionary<string, SalesAccount> dsa = new Dictionary<string, SalesAccount>();

        public void Code(ISYN handler, CodeResult result, SYNRight user, SerialType st, String parameter)
        {

            List<E01A09E> E = new List<E01A09E>();
            E01A09P P = (E01A09P)handler.Serial.Deserialize(st, typeof(E01A09P), parameter);
            if (!P.ListAdjustAccount.Equals("[]"))
            {
                E = (List<E01A09E>)handler.Serial.Deserialize(st, typeof(List<E01A09E>), P.ListAdjustAccount);
            }

            try
            {
                SqlParameter[] sps = new SqlParameter[10 + E.Count * 8];
                sps[0] = new SqlParameter("@ID", SqlDbType.NVarChar, 50);
                sps[0].Value = P.ID;
                sps[1] = new SqlParameter("@Number", SqlDbType.NVarChar, 50);
                sps[1].Value = P.Number;
                sps[2] = new SqlParameter("@EnableTime", SqlDbType.DateTime);
                sps[2].Value = Convert.ToDateTime(P.EnableTime);
                sps[3] = new SqlParameter("@MakeTime", SqlDbType.DateTime);
                sps[3].Value = Convert.ToDateTime(P.MakeTime);
                sps[4] = new SqlParameter("@CheckTime", SqlDbType.DateTime);
                sps[4].Value = Convert.ToDateTime(P.CheckTime);
                sps[5] = new SqlParameter("@AdjustMode", SqlDbType.Int);
                sps[5].Value = P.AdjustMode;
                sps[6] = new SqlParameter("@IsEnableNow", SqlDbType.Bit);
                sps[6].Value = P.IsEnableNow;
                sps[7] = new SqlParameter("@Remark", SqlDbType.NVarChar, 50);
                sps[7].Value = P.Remark;
                sps[8] = new SqlParameter("@MultiCheckStatus", SqlDbType.Int);
                sps[8].Value = P.MultiCheckStatus;
                sps[9] = new SqlParameter("@IsExecuted", SqlDbType.Bit);
                sps[9].Value = P.IsExecuted;

                //AccountISN = new string[E.Count];
                

                for (int i = 0; i < E.Count; i++)
                {
                    //AccountISN[i] = E[i].SourceISN;
                    if (i == (E.Count -1))
                    {
                        strAccountISN = strAccountISN + E[i].SourceISN;
                    }
                    else 
                    {
                        strAccountISN = strAccountISN + E[i].SourceISN + "," ;
                    }
                    
                    sps[10 + 8 * i] = new SqlParameter("@AccountNo" + i.ToString(), SqlDbType.NChar, 50);
                    sps[10 + 8 * i].Value = E[i].AccountNo;
                    sps[11 + 8 * i] = new SqlParameter("@AccountName" + i.ToString(), SqlDbType.NChar, 50);
                    sps[11 + 8 * i].Value = E[i].AccountName;
                    sps[12 + 8 * i] = new SqlParameter("@ProInfo" + i.ToString(), SqlDbType.NChar, 50);
                    sps[12 + 8 * i].Value = E[i].ProInfo;
                    sps[13 + 8 * i] = new SqlParameter("@RawPolicy" + i.ToString(), SqlDbType.NChar, 50);
                    sps[13 + 8 * i].Value = E[i].RawPolicy;
                    sps[14 + 8 * i] = new SqlParameter("@RawPrice" + i.ToString(), SqlDbType.Decimal);
                    sps[14 + 8 * i].Value = E[i].RawPrice;
                    sps[15 + 8 * i] = new SqlParameter("@AdjustPrice" + i.ToString(), SqlDbType.Decimal);
                    sps[15 + 8 * i].Value = E[i].AdjustPrice;
                    sps[16 + 8 * i] = new SqlParameter("@SourceISN" + i.ToString(), SqlDbType.NChar,50);
                    sps[16 + 8 * i].Value = E[i].SourceISN;
                    sps[17 + 8 * i] = new SqlParameter("@Index" + i.ToString(), SqlDbType.Int);
                    sps[17 + 8 * i].Value = E[i].Index;
                    
                }
                //给字典类型赋值
                //GetSalesAccount(handler);  
                dsa = handler.Data.ExeSalesAccount(P.BaseNo, strAccountISN);

                StringBuilder sql = new StringBuilder();
                sql.Append(" SET NOCOUNT ON\r\n");
                sql.Append("DECLARE @Type AS  NVARCHAR(50) ");
                sql.Append("DECLARE @ErrorCount AS INT ");
                sql.Append("SET @ErrorCount=0 ");
                sql.Append("DECLARE @FID INT SET @FID = IsNull((SELECT FID FROM KEW_SalesReadjust WHERE FText2 =@ID),0)\r\n");
                sql.Append("BEGIN TRAN \r\n");
                sql.Append("DECLARE @Count INT SET @Count=IsNull((SELECT 1 FROM KEW_SalesReadjust WHERE FBillNo=@Number),0)");
                sql.Append("IF @Count>0 BEGIN\r\n");
                sql.Append("  UPDATE KEW_SalesReadjust SET FComboBox=@AdjustMode,FTime1=@EnableTime,FTime=@MakeTime,FNOTE=@Remark,FCheckBox1=@IsEnableNow,FCheckBox=@IsExecuted WHERE FBillNo=@Number\r\n");
                sql.Append("  SET @ErrorCount=@ErrorCount+@@ERROR ");
                sql.Append("  SET @Type ='U'\r\n");
                sql.Append("END ELSE BEGIN\r\n");
                sql.Append("  EXEC GetICMaxNum 'KEW_SalesReadjust',@FID OUTPUT\r\n");
                sql.Append("  INSERT INTO KEW_SalesReadjust ([FClassTypeID],[FID],[FBillNo],[FComboBox],[FTime1],[FTime],[FTime2],[FNOTE],[FCheckBox1],[FCheckBox],[FBiller],[FUser],[FText2]) ");
                sql.Append("  VALUES (236900151,@FID,@Number,@AdjustMode,@EnableTime,@MakeTime,@CheckTime,@Remark,@IsEnableNow,0,0,0,@ID)\r\n");
                sql.Append("  SET @ErrorCount=@ErrorCount+@@ERROR ");
                sql.Append("  SET @Type ='I'\r\n");
                sql.Append("END \r\n");

                sql.Append("DECLARE @AccountFID AS INT ");
                sql.Append("DECLARE @AccountNo AS  NVARCHAR(50) ");
                sql.Append("DECLARE @AccountNameFID INT\r\n");
                sql.Append("DECLARE @ProInfoFID INT\r\n ");

                for (int i = 0; i < E.Count; i++)
                {
                    String ISN = E[i].SourceISN;
                    if (dsa != null)
                    {
                        if (dsa.Count != E.Count)
                        {
                            if (dsa.ContainsKey(ISN))
                            {
                                sql.Append(" SET @AccountFID=" + dsa[ISN].AccountFID + "\r\n");
                                sql.Append(" SET @AccountNo='" + dsa[ISN].AccountNo + "'\r\n");
                            }
                            else
                            {
                                sql.Append("  SELECT 'FALSE', '销售账户三方内码" + ISN + "对应错误！'\r\n");
                                sql.Append("  SET @ErrorCount=@ErrorCount+1 ");
                                //sql.Append("  RETURN END\r\n");
                                
                            }
                        }
                        else
                        {
                            if (dsa.ContainsKey(ISN))
                            {
                                sql.Append(" SET @AccountFID=" + dsa[ISN].AccountFID + "\r\n");
                                sql.Append(" SET @AccountNo='" + dsa[ISN].AccountNo + "'\r\n");
                            }
                            else
                            {
                                sql.Append("  SELECT 'FALSE', '销售账户三方内码" + ISN + "对应错误！'\r\n");
                                sql.Append("  SET @ErrorCount=@ErrorCount+ 1 ");
                                //sql.Append("  RETURN END\r\n");
                            }

                        }

                        sql.Append(" SET @AccountNameFID = IsNull((SELECT FItemID FROM t_Organization WHERE FHomePage=@AccountName" + i.ToString() + " ),0)\r\n");
                        sql.Append(" SET @ProInfoFID = IsNull((SELECT FID FROM KEW_ProductsEntry WHERE FText =@ProInfo" + i.ToString() + " ),0)\r\n");
                        sql.Append("IF (SELECT COUNT(1) FROM KEW_SalesReadjustEntry WHERE FID =@FID AND FIndex=@Index" + i.ToString() + " ) > 0 BEGIN\r\n ");
                        sql.Append("  UPDATE KEW_SalesReadjustEntry SET FDecimal3=@RawPrice" + i.ToString() + " ,FDecimal4=@AdjustPrice" + i.ToString() + ",FText=@RawPolicy" + i.ToString() + ", FText1=@AccountNo" + i.ToString() + ", FBase=@AccountNameFID, FBase1=@ProInfoFID WHERE FID =@FID AND FIndex=@Index" + i.ToString() + " \r\n");
                        sql.Append("END ELSE BEGIN\r\n");
                        sql.Append("  INSERT INTO KEW_SalesReadjustEntry ([FClassID_SRC],[FID],[FIndex],[FDecimal3],[FDecimal4],[FText],[FText1],[FBase],[FBase1],[FID_SRC],[FBillNo_SRC]) VALUES (236900147,@FID,@Index" + i.ToString() + ",@RawPrice" + i.ToString() + ",@AdjustPrice" + i.ToString() + ",@RawPolicy" + i.ToString() + ",@AccountNo" + i.ToString() + ",@AccountNameFID,@ProInfoFID,@AccountFID,@AccountNo)\r\n ");
                        sql.Append("END \r\n");
                        sql.Append("  SET @ErrorCount=@ErrorCount+@@ERROR ");
                    }
                }
                //执行存储过程  审核人未确定
                sql.Append("EXEC KEW_SALES_APPLYREADJUST @FID,'0' \r\n");
                sql.Append("IF @ErrorCount=0 AND (SELECT COUNT(1) FROM KEW_SalesReadjust WHERE FBillNo=@Number)=1 ");
                sql.Append("BEGIN ");
                sql.Append("SELECT @Type,@FID\r\n ");
                sql.Append("COMMIT TRAN ");
                sql.Append("END ");
                sql.Append("ELSE BEGIN ");
                sql.Append("SELECT 'FALSE','事务出错回滚' ");
                sql.Append("ROLLBACK TRAN ");
                sql.Append("END ");

                sql.Append(" SET NOCOUNT OFF\r\n");
                Recordset rs = handler.Data.ExeProcedure(P.BaseNo, sql.ToString(), sps);
                if (rs.Enable)
                {
                    if (rs.Data.Tables[0].Rows[0][0].ToString() == "U")
                    {
                        result.Result = EnumResult.Update;
                        result.Content = rs.Data.Tables[0].Rows[0][1].ToString();
                    }
                    else
                    {
                        result.Result = EnumResult.Insert;
                        result.Content = rs.Data.Tables[0].Rows[0][1].ToString();
                    }

                    result.Message = String.Format("销售调价同步完成:{0},{1}", P.Number, result.Result.ToString());
                }
                else
                {
                    result.Result = EnumResult.None;
                    result.Message = String.Format("销售调价同步失败:{0}", rs.Message);
                }
            }
            catch (Exception ex)
            {
                result.Result = EnumResult.None;
                result.Message = String.Format("销售调价同步失败:{0}", ex.Message);
            }
        }

    }

    /// <summary>
    /// 销售调价
    /// </summary>
    public class E01A09P
    {
        /// <summary>
        /// 账套编号
        /// </summary>
        public String BaseNo;
        /// <summary>
        /// 三方内码
        /// </summary>
        public String ID;
        /// <summary>
        /// 三方编号
        /// </summary>
        public String Number;
        /// <summary>
        /// 生效时间
        /// </summary>
        public String EnableTime;
        /// <summary>
        /// 制单时间
        /// </summary>
        public String MakeTime;
        /// <summary>
        /// 调整方式
        /// </summary>
        public int AdjustMode;
        /// <summary>
        /// 已执行
        /// </summary>
        public Boolean IsExecuted;
        /// <summary>
        /// 立即生效
        /// </summary>
        public Boolean IsEnableNow;
        /// <summary>
        /// 审核时间
        /// </summary>
        public String CheckTime;
        /// <summary>
        /// 备注
        /// </summary>
        public String Remark;
        /// <summary>
        /// 审批流程状态（）
        /// </summary>
        public int MultiCheckStatus;
        /// <summary>
        /// 销售账户
        /// </summary>
        public String ListAdjustAccount;

    }
    /// <summary>
    /// 销售调价-销售账户
    /// </summary>
    public class E01A09E
    {
        /// <summary>
        ///调价单顺序号
        /// </summary>
        public int Index;
        /// <summary>
        /// 账户编号
        /// </summary>
        public String AccountNo;
        /// <summary>
        /// 客户名称
        /// </summary>
        public String AccountName;
        /// <summary>
        /// 产品
        /// </summary>
        public String ProInfo;
        /// <summary>
        /// 原政策
        /// </summary>
        public String RawPolicy;
        /// <summary>
        /// 原单价
        /// </summary>
        public decimal RawPrice;
        /// <summary>
        /// 调整单价
        /// </summary>
        public decimal AdjustPrice;
        /// <summary>
        /// 源单内码
        /// </summary>
        public String SourceISN;
        /// <summary>
        /// 源单编号
        /// </summary>
       // public String SourceBillNo;

    }
}
